package com.tsd.jxc.sale.controller;

import com.alibaba.fastjson.JSON;
import com.tsd.core.annotation.CheckBind;
import com.tsd.core.annotation.DataPermission;
import com.tsd.core.constants.Constants;
import com.tsd.core.datasource.DataSourceContextHolder;
import com.tsd.core.utils.HlpUtils;
import com.tsd.core.utils.ListUtil;
import com.tsd.core.vo.ErrorCode;
import com.tsd.core.vo.HlpException;
import com.tsd.core.vo.HttpResult;
import com.tsd.core.vo.PageBean;
import com.tsd.jxc.fin.job.JxcFinanceJob;
import com.tsd.jxc.req.JxcSaleOrderReqParamsVo;
import com.tsd.jxc.req.JxcSaleReturnBillReqParamsVo;
import com.tsd.jxc.sale.dao.JxcSaleOrderDetailMapper;
import com.tsd.jxc.sale.entity.JxcSaleOrderDetailExt;
import com.tsd.jxc.sale.entity.JxcSaleOrderExt;
import com.tsd.jxc.sale.entity.JxcSaleReturnBillExt;
import com.tsd.jxc.sale.service.JxcSaleOrderService;
import com.tsd.jxc.sale.vo.JxcSaleOrderExportVo;
import com.tsd.jxc.setting.service.JxcSettingService;
import com.tsd.jxc.utils.JxcAutoApprovalUtil;
import com.tsd.jxc.vo.JxcSettingVo;
import com.tsd.jxc.vo.PrintVo;
import com.tsd.system.controller.SystemBaseController;
import com.tsd.system.entity.SysUser;
import com.tsd.system.entity.SysUserExt;
import com.tsd.system.service.SystemSettingService;
import com.tsd.system.vo.GlobalSetting;
import com.tsd.thread.Callback;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 描述：JxcSaleOrder销售订单 控制层
 *
 * @author Hillpool
 * @date 2022/07/29 15:04:27
 */
@Controller
@Scope("prototype")
@RequestMapping("/api/v2")
@Api(tags = "进销存-销售订单", description = "销售订单的API描述")
public class JxcSaleOrderController extends SystemBaseController {

    @Resource
    private JxcSaleOrderService jxcSaleOrderService;
    @Resource
    private JxcSaleOrderDetailMapper jxcSaleOrderDetailMapper;
    @Resource
    private JxcFinanceJob jxcFinanceJob;
    @Resource
    private SystemSettingService systemSettingService;
    @Resource
    private JxcSettingService jxcSettingService;

    @ApiOperation(value = "根据sid获取销售订单", notes = "根据sid获取销售订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sid", value = "销售订单sid", required = true, dataType = "string", paramType = "form")
    })
    @ResponseBody
    @RequestMapping(value = "/getJxcSaleOrderBySid.action", method = RequestMethod.POST)
    public HttpResult<Object> getJxcSaleOrderBySid() {
        return this.getJxcSaleOrderBySidMethod();
    }


    public HttpResult<Object> getJxcSaleOrderBySidMethod() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUser opUser = super.getSysUser();
            Map<String, Object> map = super.getParams(request);
            String sid = HlpUtils.getString(map, "sid");
            super.checkEmpty(sid, "请提供参数sid");
            JxcSaleOrderExt orderExt = jxcSaleOrderService.queryBySid(sid);
            if (orderExt != null) {
                GlobalSetting setting = systemSettingService.getGlobalSetting();
                setting.procDisplay(orderExt, GlobalSetting.TYPE_CLIENT);
                List<JxcSaleOrderDetailExt> detailExtList = orderExt.getDetail_list();
                if (!HlpUtils.isEmptyList(detailExtList)) {
                    ListUtil.forEach(detailExtList, t -> setting.procDisplay(t, GlobalSetting.TYPE_CLIENT));
                    orderExt.setDetail_list(detailExtList);
                }
            }
            JxcSettingVo settingVo = jxcSettingService.getJxcSettingVo(DataSourceContextHolder.getDataSourceType());
            if (settingVo.isClothing()) {
                if (map.containsKey("export")) {
                    hr.setData(JxcSaleOrderExportVo.transfer(orderExt, settingVo, opUser));
                } else {
                    hr.setData(JxcSaleOrderReqParamsVo.transfer(orderExt, settingVo));
                }
            } else {
                hr.setData(orderExt);
            }
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "根据id删除销售订单", notes = "根据id删除销售订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sids", value = "销售订单sids", required = true, dataType = "string", paramType = "form")
    })
    @ResponseBody
    @RequestMapping(value = "/deleteJxcSaleOrders.action", method = RequestMethod.POST)
    public HttpResult<String> deleteJxcSaleOrders() {
        HttpResult<String> hr = new HttpResult<>();
        try {
            SysUser opUser = super.getSysUser();
            Map<String, Object> map = super.getParams(request);
            Object sids = map.get("sids");
            super.checkEmpty(sids, "请提供参数sids");
            List<String> list = JSON.parseArray(JSON.toJSONString(sids), String.class);
            jxcSaleOrderService.deleteJxcSaleOrders(list, opUser);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }


    @ApiOperation(value = "保存销售订单", notes = "保存销售订单，具有id值则更新，没有id值则新增")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "obj", value = "销售订单", required = true, paramType = "body", dataType = "JxcSaleOrder")
    })
    @ResponseBody
    @RequestMapping(value = "/saveJxcSaleOrder.action", method = RequestMethod.POST)
    @CheckBind(person = true)
    public HttpResult<Object> saveJxcSaleOrder() {
        return this.saveJxcSaleOrderMethod(false, null);
    }


    public HttpResult<Object> saveJxcSaleOrderMethod(boolean isXd, Callback<JxcSaleOrderExt> callback) {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUserExt opUser = super.getSysUser();
            JxcSaleOrderReqParamsVo paramsVo = super.getParams(request, JxcSaleOrderReqParamsVo.class);
            JxcSaleOrderExt orderExt = paramsVo.convert();
            if (HlpUtils.isEmpty(orderExt.getId()) && HlpUtils.isEmpty(orderExt.getSalesman_sid())) {
                orderExt.setSalesman_sid(opUser.getGroup_person_sid());
            }
            if (callback != null) {
                callback.pre_action(orderExt, opUser);
            }
            if (isXd) {
                jxcSaleOrderService.checkBuyStock(orderExt);
            }
            jxcSaleOrderService.saveJxcSaleOrder(orderExt, opUser);
            JxcSettingVo settingVo = jxcSettingService.getJxcSettingVo(DataSourceContextHolder.getDataSourceType());
            // 判断是否自动审核
            JxcAutoApprovalUtil.autoApproval(JxcAutoApprovalUtil.FIELD_AUTO_APPROVAL_SALE_ORDER, () -> {
                opUser.setDr(0);
                if (isXd) {
                    jxcSaleOrderService.changeJxcSaleOrderAuditStateWithCheckStock(Collections.singletonList(orderExt.getSid()), 1, null, "1", opUser);
                } else {
                    jxcSaleOrderService.changeJxcSaleOrderAuditState(Collections.singletonList(orderExt.getSid()), 1, settingVo, opUser);
                }
            });
            if (callback != null) {
                callback.post_action(orderExt, opUser);
            }
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "分页查询销售订单", notes = "分页查询销售订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "名称", required = false, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "pageNo", value = "页码", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "pageSize", value = "页大小，每页记录数", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "sorts", value = "排序设置，方式['property1 desc','property2']", required = false, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "totalRows", value = "总记录数，为了减少统计总记录数，一般从第二页开始前端提供totalRows", required = false, dataType = "int", paramType = "form")
    })
    @ResponseBody
    @RequestMapping(value = "/findJxcSaleOrders.action", method = RequestMethod.POST)
    @DataPermission(code = "saleOrder")
    public HttpResult<Object> findJxcSaleOrders() {
        return this.findJxcSaleOrderList();
    }

    private HttpResult<Object> findJxcSaleOrderList() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            Map<String, Object> params = super.getDataPermissionParams();
            HlpUtils.copyIntegerValue(map, params, "dr", "dr", false, 0);
            HlpUtils.copyIntegerValue(map, params, "state", "state", false, null);
            HlpUtils.copyIntegerValue(map, params, "audit_state", "audit_state", false, null);
            HlpUtils.copyIntegerValue(map, params, "order_type", "order_type", false, null);
            HlpUtils.copyIntegerValue(map, params, "un_receive", "un_receive", false, null);
            HlpUtils.copyIntegerValue(map, params, "invoice_state", "invoice_state", false, null);
            HlpUtils.copyStringValue(map, params, "code", "code", false, false);
            HlpUtils.copyStringValue(map, params, "client_sid", "client_sid", false, false);
            HlpUtils.copyStringValue(map, params, "client_name", "client_name", false, false);
            HlpUtils.copyStringValue(map, params, "office_contract_name", "office_contract_name", false, false);
            HlpUtils.copyStringValue(map, params, "select_order", "select_order", false, false);
            HlpUtils.copyStringValue(map, params, "contract_code", "contract_code", false, false);
            HlpUtils.copyStringValue(map, params, "search_value", "search_value", false, true);
            HlpUtils.copyStringValue(map, params, "goods_name", "goods_name", false, true);
            HlpUtils.copyDateRangeValue(map, params, "order_date", false);
            HlpUtils.copyDateRangeValue(map, params, "client_req_delivery_date", false);
            HlpUtils.copyDateRangeValue(map, params, "client_req_receive_date", false);
            HlpUtils.copyDateRangeValue(map, params, "pre_delivery_date", false);
            HlpUtils.copyDateRangeValue(map, params, "real_delivery_date", false);
            HlpUtils.copyDateRangeValue(map, params, "audit_date", false);
            HlpUtils.copyListValue(map, params, "person_list", "person_list", false, String.class);
            super.filterGroups(map, params);
            PageBean page = new PageBean(map);
            if (map.containsKey(Constants.KEY_NO_PAGE)) {
                page = null;
            }
            List<JxcSaleOrderExt> list = jxcSaleOrderService.findJxcSaleOrders(params, page);
            if (map.containsKey("with_detail")) {
                List<String> orderList = ListUtil.map(list, JxcSaleOrderExt::getSid);
                JxcSaleOrderDetailExt detailParams = new JxcSaleOrderDetailExt();
                detailParams.setDr(0);
                detailParams.setOrder_list(orderList);
                List<JxcSaleOrderDetailExt> detailExtList = jxcSaleOrderDetailMapper.selectByEntity(detailParams);
                for (JxcSaleOrderExt orderExt : list) {
                    List<JxcSaleOrderDetailExt> filterList = ListUtil.filter(detailExtList, t -> t.getOrder_sid().equals(orderExt.getSid()));
                    orderExt.setDetail_list(filterList);
                }
            }
            if (!HlpUtils.isEmptyList(list)) {
                GlobalSetting setting = systemSettingService.getGlobalSetting();
                ListUtil.forEach(list, t -> {
                    setting.procDisplay(t, GlobalSetting.TYPE_CLIENT);
                    if (!HlpUtils.isEmptyList(t.getDetail_list())) {
                        ListUtil.forEach(t.getDetail_list(), detail -> setting.procDisplay(detail, GlobalSetting.TYPE_CLIENT));
                    }
                });
            }
            hr.setData(list);
            hr.setPage(page);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    /**
     * 审核/反审核
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/changeJxcSaleOrderAuditState.action", method = RequestMethod.POST)
    @CheckBind(person = true)
    public HttpResult<Object> changeJxcSaleOrderAuditState() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUserExt opUser = super.getSysUser();
            Map<String, Object> map = super.getParams(request);
            Integer state = HlpUtils.getInteger(map, "state");
            super.checkEmpty(state, "请提供参数：state");
            if (!Arrays.asList(1, -1).contains(state)) {
                throw new HlpException("state值错误：1-审核、-1-反审核");
            }
            List<String> sidList = super.getParamsList(map, "sid_list", String.class, true);
            JxcSettingVo settingVo = jxcSettingService.getJxcSettingVo(DataSourceContextHolder.getDataSourceType());
            jxcSaleOrderService.changeJxcSaleOrderAuditState(sidList, state, settingVo, opUser);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    /**
     * 生成出库单
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/genJxcSaleOrder2OutBill.action", method = RequestMethod.POST)
    public HttpResult<Object> genJxcSaleOrder2OutBill() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUserExt opUser = super.getSysUser();
            Map<String, Object> map = super.getParams(request);
            List<String> sidList = super.getParamsList(map, "sid_list", String.class, true);
            jxcSaleOrderService.genJxcSaleOrder2OutBill(sidList, opUser);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    /**
     * 生成退货单
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/genJxcSaleOrder2ReturnBill.action", method = RequestMethod.POST)
    public HttpResult<Object> genJxcSaleOrder2ReturnBill() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUserExt opUser = super.getSysUser();
            Map<String, Object> map = super.getParams(request);
            List<String> sidList = super.getParamsList(map, "sid_list", String.class, true);
            jxcSaleOrderService.genJxcSaleOrder2ReturnBill(sidList, opUser);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    /**
     * 获取退货单数据
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getJxcSaleOrder2ReturnBillData.action", method = RequestMethod.POST)
    public HttpResult<Object> getJxcSaleOrder2ReturnBillData() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            String sid = HlpUtils.getString(map, "sid");
            super.checkEmpty(sid, "请提供参数sid");
            JxcSaleReturnBillExt billExt = jxcSaleOrderService.getJxcSaleOrder2ReturnBillData(sid);
            if (billExt != null) {
                GlobalSetting setting = systemSettingService.getGlobalSetting();
                setting.procDisplay(billExt, GlobalSetting.TYPE_CLIENT);
            }
            JxcSettingVo settingVo = jxcSettingService.getJxcSettingVo(DataSourceContextHolder.getDataSourceType());
            if (settingVo.isClothing()) {
                hr.setData(JxcSaleReturnBillReqParamsVo.transfer(billExt, settingVo));
            } else {
                hr.setData(billExt);
            }
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    /**
     * 生成对账
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/genJxcFinanceAccountDetail4Sale.action", method = RequestMethod.POST)
    public HttpResult<Object> genJxcFinanceAccountDetail4Sale() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUserExt opUser = super.getSysUser();
            Map<String, Object> map = super.getParams(request);
            List<String> sidList = super.getParamsList(map, "sid_list", String.class, true);
            Integer genNum = jxcSaleOrderService.genJxcFinanceAccountDetail4Sale(sidList, opUser);
            if (genNum > 0) {
                jxcFinanceJob.addAccountSet2PriorityQueue4Finance(DataSourceContextHolder.getDataSourceType());
                hr.setData(genNum);
                hr.setCode(ErrorCode.CODE_SUCCESS);
            } else {
                hr.setData(genNum);
                hr.setMessage("没有符合条件的记录");
                hr.setCode(ErrorCode.CODE_NO_DATA);
            }
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "打印获取销售订单数据", notes = "打印获取销售订单数据")
    @ResponseBody
    @RequestMapping(value = "/queryJxcSaleOrderData4Print.action", method = RequestMethod.POST)
    public HttpResult<Object> queryJxcSaleOrderData4Print() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUserExt opUser = super.getSysUser();
            List<String> sidList = super.getParamsList("sid_list", String.class, true);
            List<JxcSaleOrderExt> list = jxcSaleOrderService.queryJxcSaleOrderData4Print(sidList);
            if (!HlpUtils.isEmptyList(list)) {
                GlobalSetting setting = systemSettingService.getGlobalSetting();
                ListUtil.forEach(list, t -> setting.procDisplay(t, GlobalSetting.TYPE_CLIENT));
            }
            List<PrintVo> voList = ListUtil.map(list, t -> t.convert2Print(opUser));
            hr.setData(voList);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "打印获取销售订单数据-雄大", notes = "打印获取销售订单数据-雄大")
    @ResponseBody
    @RequestMapping(value = "/queryXdSaleOrderData4Print.action", method = RequestMethod.POST)
    public HttpResult<Object> queryXdSaleOrderData4Print() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUserExt opUser = super.getSysUser();
            List<String> sidList = super.getParamsList("sid_list", String.class, true);
            List<JxcSaleOrderExt> list = jxcSaleOrderService.queryXdSaleOrderData4Print(sidList);
            if (!HlpUtils.isEmptyList(list)) {
                GlobalSetting setting = systemSettingService.getGlobalSetting();
                ListUtil.forEach(list, t -> setting.procDisplay(t, GlobalSetting.TYPE_CLIENT));
            }
            List<PrintVo> voList = ListUtil.map(list, t -> t.convert2Print(opUser));
            hr.setData(voList);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    /**
     * 审核/反审核-检查采购单库存
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/changeJxcSaleOrderAuditStateWithCheckStock.action", method = RequestMethod.POST)
    @CheckBind(person = true)
    public HttpResult<Object> changeJxcSaleOrderAuditStateWithCheckStock() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUserExt opUser = super.getSysUser();
            Map<String, Object> map = super.getParams(request);
            Integer state = HlpUtils.getInteger(map, "state");
            String execute = HlpUtils.getString(map, "execute");
            String related_audit = HlpUtils.getString(map, "related_audit");
            super.checkEmpty(state, "请提供参数：state");
            if (!Arrays.asList(1, -1).contains(state)) {
                throw new HlpException("state值错误：1-审核、-1-反审核");
            }
            List<String> sidList = super.getParamsList(map, "sid_list", String.class, true);
            hr = jxcSaleOrderService.changeJxcSaleOrderAuditStateWithCheckStock(sidList, state, execute, related_audit, opUser);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    /**
     * 作废
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/cancelJxcSaleOrder.action", method = RequestMethod.POST)
    @CheckBind(person = true)
    public HttpResult<Object> cancelJxcSaleOrder() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUserExt opUser = super.getSysUser();
            List<String> sidList = super.getParamsList("sid_list", String.class, true);
            jxcSaleOrderService.cancelJxcSaleOrder(sidList, opUser);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

}
